// -------------------------------------------------
// BlinKit - BkBase Library
// -------------------------------------------------
//   File Name: request_impl_win.cpp
// Description: RequestImpl Class
//      Author: Ziming Li
//     Created: 2022-09-23
// -------------------------------------------------
// Copyright (C) 2022 MingYang Software Technology.
// -------------------------------------------------

#include "./request_impl.h"

#include "third_party/zed/include/zed/string/algorithm.hpp"
#include "third_party/zed/include/zed/win/hmodule.hpp"
#include "third_party/zed/include/zed/win/registry.hpp"

static std::string ParseProxy(const zed::url &URL, const std::string &proxy)
{
    auto parts = zed::split(proxy, ";");
    for (const auto &part : parts)
    {
        size_t p = part.find('=');
        if (std::string_view::npos == p)
            return std::string(part);

        std::string scheme(part.substr(0, p));
        if (URL.scheme_is(scheme.c_str()))
            return std::string(part.substr(p + 1));
    }
    return std::string();
}

void RequestImpl::GetSystemProxy(bool &enabled, std::string &proxy, std::string &pac) const
{
    enabled = false;

    zed::reg_key k = zed::reg_key::open(HKEY_CURRENT_USER,
        R"(Software\Microsoft\Windows\CurrentVersion\Internet Settings)",
        KEY_QUERY_VALUE);
    if (!k)
        return;

    DWORD proxyEnable = 0;
    if (k.query_value("ProxyEnable", proxyEnable) && proxyEnable)
        enabled = true;

    std::string proxyServer;
    if (k.query_value("ProxyServer", proxyServer) && !proxyServer.empty())
        proxy = ParseProxy(CurrentURL(), proxyServer);

    k.query_value("AutoConfigURL", pac);
}

bool RequestImpl::IsJSLoaded(void)
{
    return nullptr != GetModuleHandle(TEXT("quickjs.dll"));
}
